/*
 * Copyright 2007-2008 Andrew O'Malley
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package ws.quokka.plugin.fop;

import org.apache.tools.ant.taskdefs.Java;

import ws.quokka.core.plugin_spi.support.AbstractPlugin;
import ws.quokka.core.plugin_spi.support.TypedProperties;

import java.io.File;


/**
 *
 */
public class FopPlugin extends AbstractPlugin {
    //~ Methods --------------------------------------------------------------------------------------------------------

    public void transform() {
        TypedProperties properties = properties();
        String options = properties.getString("options", "");
        String configuration = properties.getString("configuration", null);
        options += (
            (configuration == null) ? ""
                                    : (
                " -c \"" + getResources().getBuildResources().getFile(configuration).getAbsolutePath() + "\""
            )
        );
        options += (" \"" + properties.getFile("in").getAbsolutePath() + "\"");
        options += (" -" + properties.getString("outputType", "pdf"));

        File output = properties.getFile("out");

        if (output != null) {
            utils().mkdir(output.getParentFile());
        }

        options += ((output == null) ? "" : (" \"" + output.getAbsolutePath() + "\""));

        Java fop = (Java) utils().init(new Java(), "fop");
        fop.setClassname("org.apache.fop.apps.Fop");
        fop.createArg().setLine(options);
        fop.setClasspath(getResources().getPathGroupAsPath("classpath"));
        fop.setFailonerror(true);
        fop.setFork(true);

        String maxMemory = properties().getString("maxMemory", null);

        if (maxMemory != null) {
            fop.setMaxmemory(maxMemory);
        }

        fop.perform();
    }
}
